//
//  UserAccount.swift
//  LVWeibo
//
//  Created by lv on 15/6/26.
//  Copyright © 2015年 lv. All rights reserved.
//

import UIKit

// swift 1.2 Printable 协议
// swift 2.0 协议变了 CustomStringConvertible
class UserAccount: NSObject,NSCoding{
    // 用于调用access_token，接口获取授权后的access token
    var access_token:String
    // access_token的生命周期，单位是秒数(实际是数值类型)
    var expires_in:NSTimeInterval
    // 过期日期(创建人:五年,普通用户:3天)
    var expiresDate:NSDate
    // 当前授权用户的UID
    var uid:String
    // 友好显示名称
    var name:String?
    // 用户头像地址（大图），180×180像素
    var avatar_large:String?
    
    //MARK:- 字典转模型
    init(dict:[String:AnyObject]) {
        access_token = dict["access_token"] as! String
        expires_in   = dict["expires_in"]   as! NSTimeInterval
        uid          = dict["uid"]          as! String
        
        // 计算过期日期
        expiresDate = NSDate(timeIntervalSinceNow: expires_in)
    }
    
    //MARK:- 根据token加载用户信息,完成回调
    func loadUserInfo(finished:(userAccount:UserAccount?,error:NSError?) -> ()) {
        
        let parameters = ["access_token":access_token,"uid":uid]
        NetWorkTools.sharedNetWorkTools.GET("2/users/show.json", parameters: parameters, success: { (_, JSON) -> Void in
            
            let dict = JSON as! [String:AnyObject]
            self.name = dict["name"] as? String
            self.avatar_large = dict["avatar_large"] as? String
            
            // 保存用户信息（此时用户信息才是完整的）
            self.saveAccount()

            // 完成回调
            finished(userAccount:self,error:nil)
            
            }) { (_, error) -> Void in
                print(error)
                finished(userAccount:nil,error:error)
        }
    }
    
    //MARK:- 保存&加载令牌
    // 保存用户信息至沙盒
    // 归档路径，注：Swift中的类常量都是用static来定义的
    static let archiverPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingPathComponent("account.plist")
    func saveAccount() {
        NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.archiverPath)
        print(UserAccount.archiverPath)
    }
    
    // 从沙盒加载用户信息
    class func loadAccount() -> UserAccount? {
        print("加载用户信息...")
        
        // 判断令牌是否有值
        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(UserAccount.archiverPath) as? UserAccount {
            // 如果沙盒存在，判断令牌是否过期,过期日期大于当前日期 降序
            if account.expiresDate.compare(NSDate()) == NSComparisonResult.OrderedDescending{
                return account
            }
        }
        return nil
    }
    
    //MARK:- NSCoding 归档接档使用的key保持一致即可
    ///  归档，aCoder 编码器，将对象转换成二进制数据保存到磁盘，和序列化很像
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    
    /// 解档 跟反序列化类似
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as! String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as! NSDate
        uid = aDecoder.decodeObjectForKey("uid") as! String
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
    
    //MARK:- 重写description方法，打印对象信息
    override var description: String {
        let properties = ["access_token","expires_in","uid","expiresDate","name","avatar_large"]
        return "\(self.dictionaryWithValuesForKeys(properties))"
    }

}
